package ex02.pyrmont;

import static f.h.dragon.util.OutUtil.out;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * Client: send request and show response
 *
 * @author Wenlong Meng(wenlong.meng@gmail.com)
 * @version 1.0 at 2012/03/11
 * @since 1.0
 */
public class Client {
	
	/**
	 * testing...
	 * 
	 * @param args
	 */
	public static void main(String[] args){
		testHttpServer();
	}

	/**
	 * test HttpServer
	 */
	public static void testHttpServer(){
		Socket socket = null;
		try {
			socket = new Socket("127.0.0.1", 8080);
			OutputStream os = socket.getOutputStream();
			InputStream is = socket.getInputStream();
			PrintWriter out = new PrintWriter(os, true);
			BufferedReader in = new BufferedReader(new InputStreamReader(is));
			//send an http request to the web server
//			out.println("GET /index.html HTTP/1.1");
			out.println("GET /SHUTDOWN HTTP/1.1");
			out.println("Host: localhost:8080");
			out.println("Connection: Close");
			out.println();
			//read the response
			boolean loop = true;
			StringBuffer sb = new StringBuffer(8096);
			while(loop){
				if(in.ready()){
					int i = 0;
					while(i != -1){
						i = in.read();
						sb.append((char)i);
					}
					loop = false;
				}
				Thread.sleep(50);
			}
			//display the response to the out console
			out(sb.toString());
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally{
			if(socket != null){
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
}
